package com.example.finalproject.order;

import com.example.finalproject.User.User;
import com.example.finalproject.car.Car;
import com.example.finalproject.car.CarService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private CarService carService;
    //添加到订单表
    @RequestMapping("/addOrder")
    public String addOrder(String carId,Model model, HttpServletRequest request){
        if(!(orderService.selectAllOrder()==null)){
            Car order_Car = carService.selectCarById(orderService.selectAllOrder().getCarId());
            model.addAttribute("order_Car",order_Car);
            model.addAttribute("error_order","请先处理已存在的订单!");
            return "order";
        }
        //根据carId找到汽车对象保存下来
        Car order_Car = carService.selectCarById(carId);
        //获取要下单汽车的名字
        HttpSession session = request.getSession();
        User order_User = (User) session.getAttribute("login_User");
        //构造方法构造一个保存了这个汽车id和用户名的order实例对象
        Order tem_Order = new Order(order_User.getUserName(),carId);
        //调用orderService的方法把这个order对象添加进数据库order表
        orderService.insertOrder(tem_Order);
        //将保存的汽车对象穿给前端订单页面显示
        model.addAttribute("order_Car",order_Car);
        return "order";
    }
    //《立即下单》
    @RequestMapping("/buyCar")
    public String buyCar(Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        User buy_User = (User) session.getAttribute("login_User");
        Order buy_order = orderService.selectOrderByUserName(buy_User.getUserName());
        Car buy_car = carService.selectCarById(buy_order.getCarId());
        System.out.println("用户:"+buy_order.getUserName()+"购买了"+buy_car.getCarName());
        model.addAttribute("buySuccessMessage","恭喜您成为了尊贵的"+buy_car.getCarName()+"车主");
        orderService.deleteOrderByUserName(buy_User.getUserName());
        return "success";
    }
    //《取消订单》
    @RequestMapping("/cancelOrder")
    public String cancelOrder(HttpServletRequest request){
        HttpSession session = request.getSession();
        User deleteOrder_User = (User) session.getAttribute("login_User");
        orderService.deleteOrderByUserName(deleteOrder_User.getUserName());
        return "index";
    }
}
